package com.jq.jqaicode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jq.jqaicode.mapper.AiChatHistoryMapper;
import com.jq.jqaicode.model.entity.AiChatHistory;
import com.jq.jqaicode.model.enums.ChatHistoryMessageTypeEnum;
import com.jq.jqaicode.service.AiChatHistoryService;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AiChatHistoryServiceImpl extends ServiceImpl<AiChatHistoryMapper, AiChatHistory> implements AiChatHistoryService {



    @Override
    public int loadChatHistoryToMemory(String appId, MessageWindowChatMemory chatMemory, int maxCount) {
        try {
            List<AiChatHistory> historyList = this.list(new QueryWrapper<AiChatHistory>()
                    .eq("app_id",appId).orderByAsc(false,"add_time")
                    .last("limit 20"));
            if (CollectionUtils.isEmpty(historyList)) {
                return 0;
            }
            // 反转列表，确保按照时间正序（老的在前，新的在后）
            historyList = historyList.reversed();
            // 按照时间顺序将消息添加到记忆中
            int loadedCount = 0;
            // 先清理历史缓存，防止重复加载
            chatMemory.clear();
            for (AiChatHistory history : historyList) {
                if (ChatHistoryMessageTypeEnum.USER.getValue().equals(history.getType())) {
                    chatMemory.add(UserMessage.from(history.getMessage()));
                } else if (ChatHistoryMessageTypeEnum.AI.getValue().equals(history.getType())) {
                    chatMemory.add(AiMessage.from(history.getMessage()));
                }
                loadedCount++;
            }
            log.info("成功为 appId: {} 加载 {} 条历史消息", appId, loadedCount);
            return loadedCount;
        } catch (Exception e) {
            log.error("加载历史对话失败，appId: {}, error: {}", appId, e.getMessage(), e);
            // 加载失败不影响系统运行，只是没有历史上下文
            return 0;
        }
    }

    @Override
    public List<ChatMessage> loadHistory(String appId) {
        // 查数据库最近limit条消息（order by created_at desc limit n），再反转为正序
        List<AiChatHistory> list = this.list(new QueryWrapper<AiChatHistory>()
                .eq("app_id",appId)
                .orderByDesc("add_time")
                .last("limit 20"));

        Collections.reverse(list);
        return list.stream().map(h -> {
            if (ChatHistoryMessageTypeEnum.AI.getValue().equals(h.getType())) {
                return AiMessage.from(h.getMessage());
            } else {
                return UserMessage.from(h.getMessage());
            }
        }).collect(Collectors.toList());
    }


    @Override
    public void addChatMessage(String appId, String message, String type, String addUser) {
        AiChatHistory aiChatHistory = new AiChatHistory();
        aiChatHistory.setAppId(appId);
        aiChatHistory.setMessage(message);
        aiChatHistory.setType(type);
        aiChatHistory.setAddUser(addUser);
        aiChatHistory.setAddTime(new Date());
        this.save(aiChatHistory);
    }
}
